import  numpy as np
import  matplotlib.pyplot as plt
from  scipy import signal
import scipy.io as sio
from scipy.interpolate import interp1d
import  neurokit2 as nk

#导入semg数据
data = sio.loadmat('ugodata.mat')
sEMG_signals1 = data['emg']
sEMG_signals = sEMG_signals1.T

fs = 1000
t = np.arange(0, 1 , 1/fs)  # 1秒钟的时间
#绘制原始信号
plt.figure(figsize=(15, 10))
for i in range(10):
    sEMG_interp_func = interp1d(np.linspace(0, 1, len(sEMG_signals[i])), sEMG_signals[i])
    sEMG_interp = sEMG_interp_func(np.linspace(0, 1, len(t)))
    plt.subplot(10, 1, i+1)
    plt.plot(t, sEMG_interp)
    plt.title(f'Raw sEMG Signal-channel{i+1}')
    plt.xlabel('Time (s)')
    plt.ylabel('Amplitude')

# 设计带通滤波器
high_cut = 499
low_cut = 20
order = 4
b,a =signal.butter(order,[low_cut/(fs/2),high_cut/(fs/2)],btype='band')


filtered_signals = []
for i in range(10):
    filtered_signal = nk.emg_clean(sEMG_signals[i-1])
    filtered_signals.append(filtered_signal)

#filtered_signals = np.array(filtered_signals)
print(filtered_signals)
#filtered_signals=np.array(filtered_signals)
#filtered_signals = filtered_signals.T
#print(filtered_signals.shape)
#filtered_signals = []
#for i in range(10):
    #filtered_signal = signal.filtfilt(b, a, sEMG_signals[i])
    #filtered_signals.append(filtered_signal)
#list_data = list(filtered_signals)
# 绘制滤波后的 sEMG 信号
plt.figure(figsize=(15, 10))
for i in range(10):
    sEMG_interp_func = interp1d(np.linspace(0, 1, len(filtered_signals[i])), filtered_signals[i])
    sEMG_interp = sEMG_interp_func(np.linspace(0, 1, len(t)))
    plt.subplot(10, 1, i+1)
    plt.plot(t, sEMG_interp)
    plt.title('Filtered sEMG Signal- Channel {i+1}')
    plt.xlabel('Time (s)')
    plt.ylabel('Amplitude')

plt.tight_layout()
plt.show()

integrated_data = {}

labeled_data1 = {'emg':filtered_signals}
array1 = np.array(list(labeled_data1.values()))
array1 = np.squeeze(array1, axis=0)
array1 = np.transpose(array1)
integrated_data["emg"]=array1

for label in data.keys():
    if isinstance(data["label"], np.ndarray):
       integrated_data["label"] = data["label"]


sio.savemat('ugodatatrans.mat',integrated_data)